from flask import Blueprint, render_template, request, jsonify, current_app
from flask_login import login_required, current_user
from sqlalchemy import desc

from applications.common import curd
from applications.common.curd import model_to_dicts, up_status, delete_one_by_id, get_one_by_id
from applications.common.helper import ModelFilter
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import xss_escape
from applications.extensions import db
from applications.models import Role
from applications.models import Article, Category
from applications.schemas import ArticleSchema

admin_article = Blueprint('adminarticle', __name__, url_prefix='/admin/article')


# 日志管理
@admin_article.get('/')
@authorize("admin:article:main")
def index():
    return render_template('admin/article/main.html')


# 获得文章数据
@admin_article.get('/data')
@authorize("admin:article:main", log=True)
def data():
    # 获取请求参数
    title = xss_escape(request.args.get('title', type=str))
    categoryid = request.args.get('categoryid', type=int)
    # 查询参数构造
    mf = ModelFilter()
    if title:
        mf.vague(field_name="title", value=title)
    if categoryid:
        mf.exact(field_name="category_id", value=categoryid)
    # orm查询
    # 使用分页获取data需要.items
    article = Article.query.filter(
        mf.get_filter(model=Article)).order_by(Article.sort.asc(),
                                               Article.id.desc()).layui_paginate()
    count = Article.query.filter(mf.get_filter(model=Article)).count()
    # 返回api
    return table_api(data=model_to_dicts(schema=ArticleSchema, data=article.items), count=count)


# 构建导出数据
@admin_article.get('/exportdata')
@authorize("admin:article:main", log=True)
def exportdata():
    # 获取请求参数
    title = xss_escape(request.args.get('title', type=str))
    categoryid = request.args.get('categoryid', type=int)
    # 查询参数构造
    mf = ModelFilter()
    if title:
        mf.contains(field_name="title", value=title)
    if categoryid:
        mf.exact(field_name="category_id", value=categoryid)
    # orm查询 导出数据不分页
    article = Article.query.filter(mf.get_filter(model=Article)).order_by(Article.sort.asc(),
                                                                          Article.id.desc())
    # 返回api
    return jsonify(data=model_to_dicts(schema=ArticleSchema, data=article))


@admin_article.get('/add/<int:aid>')
@authorize("admin:article:add", log=True)
def add(aid):
    coverimgscale = current_app.config.get("COVERIMG_SCALE")
    lunboimgscale = current_app.config.get("LUNBOIMG_SCALE")
    coverimgwidht = current_app.config.get("COVERIMG_WIDTH")
    lunboimgwidth = current_app.config.get("LUNBOIMG_WIDTH")
    if aid > 0:
        earticle = Article.query.filter_by(id=aid).first()
        return render_template("admin/article/add.html", coverimgscale=coverimgscale, lunboimgscale=lunboimgscale,
                               coverimgwidht=coverimgwidht, lunboimgwidth=lunboimgwidth, earticle=earticle)
    return render_template("admin/article/add.html", coverimgscale=coverimgscale, lunboimgscale=lunboimgscale,
                           coverimgwidht=coverimgwidht, lunboimgwidth=lunboimgwidth)


@admin_article.get("/test")
def test():
    return render_template("admin/article/test.html")


# 保存文章
@admin_article.post('/save')
@authorize("admin:article:add", log=True)
def save():
    req_json = request.json
    aid = req_json.get("aid")
    title = xss_escape(req_json.get('title'))
    category_id = xss_escape(req_json.get("categoryid"))
    linkurl = xss_escape(req_json.get("linkurl"))
    author = xss_escape(req_json.get("author"))
    coverimg = xss_escape(req_json.get("coverimg"))
    sort = xss_escape(req_json.get("sort"))
    lunbo = req_json.get("lunbo")
    lunboimg = req_json.get("lunboimg")
    allsort = req_json.get("allsort")
    literemark = xss_escape(req_json.get("literemark"))
    release_time = xss_escape(req_json.get("releasetime"))
    ip = request.remote_addr
    remark = req_json.get("remark")
    status = req_json.get("status")
    releaseuser = current_user.id
    if not title:
        return fail_api(msg="标题或能为空！")
    if not remark:
        return fail_api(msg="内容不能为空！")
    if not category_id:
        return fail_api(msg="分类选项不能为空！")

    newarticle = Article(title=title, category_id=category_id, linkurl=linkurl, author=author, coverimg=coverimg,
                         lunbo=lunbo, lunboimg=lunboimg, allsort=allsort, sort=sort, release_time=release_time,
                         ip=ip, remark=remark, literemark=literemark, status=status, releaseuser=releaseuser)
    id = int(aid)
    if id > 0:
        newdata = {
            "title": title, "category_id": category_id, "linkurl": linkurl, "author": author, "coverimg": coverimg,
            "lunbo": lunbo, "lunboimg": lunboimg, "allsort": allsort, "sort": sort, "release_time": release_time,
            "ip": ip, "remark": remark, "literemark": literemark, "status": status, "releaseuser": releaseuser
        }
        d = Article.query.filter_by(id=id).update(newdata)
        if not d:
            return fail_api(msg="更新失败")
        else:
            db.session.commit()
            return success_api(msg="更新成功")
    else:
        db.session.add(newarticle)
    db.session.commit()
    return success_api(msg="添加成功")


# 审核文章
@admin_article.put('/enable')
@authorize("admin:article:edit", log=True)
def enable():
    _id = request.json.get('id')
    _status = request.json.get('status')
    if _id:
        res = up_status(model=Article, id=_id, status=_status)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="审核成功")
    return fail_api(msg="数据错误")


# 删除单个文章
@admin_article.delete('/remove/<int:id>')
@authorize("admin:article:remove", log=True)
def remove(id):
    res = delete_one_by_id(Article, id)
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")


# 批量删除文章
# 批量删除
@admin_article.delete('/batchRemove')
@authorize("admin:article:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        Article.query.filter_by(id=id).delete()
        db.session.commit()
    return success_api(msg="批量删除成功")


# 更新排序
@admin_article.put('/editfield')
@authorize("admin:article:edit", log=True)
def editfield():
    id = request.json.get('id')
    field = request.json.get('field')
    value = request.json.get('value')
    article = get_one_by_id(Article, id)
    if field == 'sort':
        article.sort = value
        db.session.commit()
    return success_api(msg="更新成功")


@admin_article.get('/profile')
@authorize("admin:article:add", log=True)
def profile():
    scale = request.args.get('scale')
    coverimg = request.args.get('coverimg')
    width = request.args.get("width")
    useold = request.args.get("useold")
    return render_template("admin/article/profile.html", imgscale=scale, coverimg=coverimg, width=width, useold=useold)
